#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import sys
import time
from configparser import ConfigParser

import requests

from common import hlog, api_config_abs_path, common_abs_path, max_error_count
from data_handle.singleton import LaGouCount, ZhiPinCount

singleton_dict = {
    "LaGou": LaGouCount,
    "ZhiPin": ZhiPinCount
}


def send_to_api(api_config, platform, data):
    try:
        hlog.enter_func("send_to_api()")
        hlog.var("api_config", api_config)
        hlog.var("data", data)

        config = ConfigParser()
        config.read(api_config_abs_path.absolute(), encoding='UTF-8')
        api_url = config['api_url_config'][api_config]

        headers = {
            "Content-Type": "application/json"
        }

        # 将解析的URL发送到addUrl的API接口
        response = requests.post(url=api_url,
                                 headers=headers,
                                 data=json.dumps(data))

        if response.status_code != requests.codes.ok:

            hlog.error("将解析的URL发送到addUrl的API接口，出错啦")
            hlog.error("调用接口的返回代码：" + response.status_code)
            hlog.error("发送失败的详情URL：" + data.get("srcUrl"))
            hlog.error("未发送成功到接口的数据：" + data)
            hlog.error("time：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        else:
            hlog.info("发送成功")
            hlog.info("time：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

            response_json = response.json()
            if response_json.get("code") == "SUCCESS":
                hlog.info("发送到kafka成功")
                hlog.info("time：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

                singleton_dict[platform].get_count()
            else:
                hlog.info("发送到kafka失败")
                hlog.info("time：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

                config = ConfigParser()
                config.read(common_abs_path.absolute(), encoding='UTF-8')
                error_json = config['error_json']["errorJson"]

                with open(error_json, "a+", encoding="UTF-8") as f:
                    f.write(json.dumps(data) + "\n")
                    f.close()

                hlog.info("数据保存到" + error_json)

                if (singleton_dict[platform].get_count(1)-1) >= max_error_count:
                    sys.exit(0)

    except Exception as e:
        hlog.error("send_to_api执行出错：" + str(e))
    finally:
        hlog.exit_func("send_to_api()")
